//
//  KDSettingController.m
//  WangJingApp
//
//  Created by 魏强 on 16/12/30.
//  Copyright © 2016年 KDTech. All rights reserved.
//

#import "KDSettingController.h"
#import "UIButton+WQExtension.h"
#import "KDLoginTool.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "GBAboutUsViewController.h"
#import "ZZPhotoKit.h"
#import "LXActionSheet.h"
#import "KDClearCacheCell.h"
#import "KDTabBarController.h"
#import "KDAccountSaveController.h"
#import "KDUpdateImgParam.h"

#define setColor WQColor(70, 89, 107) //设置界面的主题色
@interface KDSettingController ()<UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate>
/**  <#Description#> */
@property (nonatomic, strong) NSArray *infoArr;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scroll_cons_w;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/**  头部view */
@property (weak, nonatomic) IBOutlet UIView *headerView;
/**  <#Description#> */
@property (nonatomic, weak) CAGradientLayer* gradientLayer;
@property (weak, nonatomic) IBOutlet UIButton *avatarBtn;
@property (weak, nonatomic) IBOutlet UILabel *nameLb;
@property (weak, nonatomic) IBOutlet UILabel *unitNameLb;
@property (weak, nonatomic) IBOutlet UILabel *changeLb;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/**  tableView的高度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *table_cons_h;

@end

@implementation KDSettingController
static NSString * const ClearCacheCellId = @"clearCache";
static NSString *cellId =@"setingCell";
static const CGFloat TopViewH = 200;
#pragma mark - 懒加载区

#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupNavbar];
    [self reloadData];
    self.view.backgroundColor = WQColor(242, 242, 242);
    self.infoArr = @[@"账户安全", @"功能介绍", @"清理缓存", @"关于我们"];
    self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    [self setupTableView];
    [self loadAvatarImage];
    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
        [self setupHeader];
//    });
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.scroll_cons_w.constant = screenW;
    
}

#pragma mark - 板块布置区

- (void)reloadData{
    KDAccount *account = [KDAccountTool account];
    self.nameLb.text = account.userName;
    self.unitNameLb.text = account.deptName;
}
- (void)setupNavbar{
    self.navigationController.navigationBar.barTintColor = setColor;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    statusBarView.backgroundColor = setColor;
    [self.navigationController.view addSubview:statusBarView];

}
/**
 *  设置渐变背景
 */
- (void)setupHeader{
    //初始化CAGradientlayer对象，使它的大小为UIView的大小
    if (!self.gradientLayer) {
        self.headerView.contentMode = UIViewContentModeScaleAspectFill;
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        self.gradientLayer = gradientLayer;
        self.gradientLayer.frame = self.headerView.bounds;
        //    KDLog(@"%@", NSStringFromCGRect(self.gradientLayer.bounds));
        //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
        [self.headerView.layer insertSublayer:self.gradientLayer atIndex:0];
        
        //设置渐变区域的起始和终止位置（范围为0-1）
        self.gradientLayer.startPoint = CGPointMake(0, 0);
        self.gradientLayer.endPoint = CGPointMake(0, 1);
        
        //设置颜色数组
        self.gradientLayer.colors = @[(__bridge id)setColor.CGColor,
                                      (__bridge id)WQColor(15, 37, 49).CGColor];
        
        //设置颜色分割点（范围：0-1）
        self.gradientLayer.locations = @[@(0.5f), @(1.0f)];
//        [self.avatarBtn setHeaderWithUrl:@"http://tva4.sinaimg.cn/crop.0.24.149.149.180/006892xejw8f3hzcquzzrj304505k3yd.jpg" forState:UIControlStateNormal placeholderStr:@"nil"];
        self.avatarBtn.layer.cornerRadius = self.avatarBtn.width *0.5;
        self.avatarBtn.clipsToBounds = YES;
        self.avatarBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;

    }
    
}
- (void)setupTableView{
    self.tableView.separatorColor = WQColor(244, 244, 244);
    self.table_cons_h.constant = 44*self.infoArr.count;
    //1.调整(iOS7以上)表格分隔线边距
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        self.tableView.separatorInset = UIEdgeInsetsZero;
    }
    //2.调整(iOS8以上)view边距(或者在cell中设置preservesSuperviewLayoutMargins,二者等效)
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        self.tableView.layoutMargins = UIEdgeInsetsZero;
    }
    [self.tableView registerClass:[KDClearCacheCell class] forCellReuseIdentifier:ClearCacheCellId];

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 向下拽了多少距离
    CGFloat down =  scrollView.contentOffset.y / 100.0;
    KDLog(@"%f", down);

    if (down > 0) return;
    
    //步骤3
//    将向下偏移的距离增加到图片高度中，图片能保持宽高比放大
    CGRect frame = self.headerView.frame;
    // 5决定图片变大的速度,值越大,速度越快
    frame.size.height = TopViewH + down * 5;
    self.avatarBtn.transform = CGAffineTransformMakeScale(1 - down, 1-down);
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    KDLog(@"%s", __func__);
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    KDLog(@"%s", __func__);
}
#pragma mark - 事件点击区
/**
 *  退出登录按钮被点击了
 */
- (IBAction)logoutBtnClick:(UIButton *)sender {
    KDBaseParam *param = [[KDBaseParam alloc]init];
//    param.method = @"logout";
    [KDLoginTool logoutWithParam:param success:^(KDBaseResult *responseObejct) {
//        if ([responseObejct.msg isEqualToString:@"操作成功"]) {//退出成功
        KDLog(@"%@",responseObejct.msg);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LogoutNoty" object:nil userInfo:nil];

            KDNewfeatureController *new  = [[KDNewfeatureController alloc]init];
            __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            [UIApplication sharedApplication].keyWindow.rootViewController = new;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            });
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**
 *  头像按钮被点击了
 *
 */
- (IBAction)avatarBtnClick:(UIButton *)sender {
    KDLog(@"%s",__func__);
    WS(ws);
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        nil;
    }];
    //添加拍照按钮
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZZCameraController *cameraController = [[ZZCameraController alloc]init];
        cameraController.takePhotoOfMax = 1;
        
        cameraController.isSaveLocal = NO;
        [cameraController showIn:ws result:^(id responseObject){
            
            
            
            NSArray *photos = (NSArray *)responseObject;
            ZZCamera *photo = photos[0];
            
            //2.上传图片
            [SVProgressHUD showWithStatus:@"上传图片中……" maskType:SVProgressHUDMaskTypeGradient];
            [ws updateImage:photo.image];

        }];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
        photoController.selectPhotoOfMax = 1;
        //设置相册中完成按钮旁边小圆点颜色。
        
        [photoController showIn:ws result:^(id responseObject){
            //1.获取到了图片
            NSArray *photos = (NSArray *)responseObject;
            ZZPhoto *photo = photos[0];
            //2.上传图片
            [SVProgressHUD showWithStatus:@"上传图片中……" maskType:SVProgressHUDMaskTypeGradient];
            [ws updateImage:photo.originImage];

            
        }];
    }];
    [sheet addAction:cancelAction];
    [sheet addAction:cameraAction];
    [sheet addAction:photoAction];
    
    [self presentViewController:sheet animated:YES completion:nil];

}

- (void)updateImage:(UIImage *)image{
    WS(ws);
    [ws uploadWithImage:image AndFinish:^(NSDictionary *result, NSError *a) {
        [SVProgressHUD dismiss];
        KDUpdateImgParam *param = [[KDUpdateImgParam alloc]init];
        param.userImage = result[@"fileUrl"];
        [KDLoginTool updateImgWithParam:param success:^(KDBaseResult *responseObejct) {
            if ([responseObejct.code isEqualToString:@"RS03SU02000"]) {
                [ws.avatarBtn setImage:image forState:UIControlStateNormal];
                //确保图片不被拉伸
//                ws.avatarBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
                
                [SVProgressHUD showSuccessWithStatus:@"修改图片成功！" maskType:SVProgressHUDMaskTypeGradient];
                KDAccount *account = [KDAccountTool account];
                account.userImage = param.userImage;
                [KDAccountTool saveAccount:account];
            }else{
                [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            }
        } failure:^(NSError *error) {
            KDLog(@"%@",error);
            [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
            
        }];
        
    }];
}

#pragma mark - 网络请求区
- (void)loadAvatarImage{
    KDAccount *account = [KDAccountTool account];
    if (account.userImage) {
        KDUpdateImgParam *param = [[KDUpdateImgParam alloc]init];
        param.userImage = account.userImage;
        NSString *url = [NSString stringWithFormat:@"%@%@userImage=%@",AuthServerAddr,@"users/downloadImage?",account.userImage];
        [self.avatarBtn setHeaderWithUrl:url forState:UIControlStateNormal placeholderStr:@"avatar_placehoder"];
    }else{
        UIImage *image = [UIImage imageNamed:@"avatar_placehoder"];
        [self.avatarBtn setImage:image forState:UIControlStateNormal];
        
    }
}
//上传图片(单张)
- (void)uploadWithImage:(UIImage*)image AndFinish:(void (^)(NSDictionary *, NSError *))finish
{
    
    //1. 存放图片的服务器地址，这里我用的宏定义
    NSString * url = @"http://monitor.szkedun.cn/fupload/submit";
    
    //2. 利用时间戳当做图片名字
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *imageName = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
    
    //3. 图片二进制文件
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
    KDLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
    
    //4. 发起网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传图片，以文件流的格式，这里注意：name是指服务器端的文件夹名字
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //上传成功时的回调
        KDLog(@"%@",responseObject);
        finish(responseObject,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败时的回调
        finish(nil,error);
    }];
}

#pragma mark - 通知接收区


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.infoArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {//缓存cell
        KDClearCacheCell *cell = [tableView dequeueReusableCellWithIdentifier:ClearCacheCellId];
        [cell updateStatus];
        return cell;
    }
    
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    //2.调整(iOS8以上)tableView边距(与上面第2步等效,二选一即可)
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = NO;
    }
    //3.调整(iOS8以上)view边距
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }

    cell.textLabel.text = self.infoArr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            KDAccountSaveController * ctr = [[KDAccountSaveController alloc]init];
//            self.navigationCont
            [self.navigationController pushViewController:ctr animated:YES];
            break;
            
        }
            
        default:
            break;
    }
    if ([self.infoArr[indexPath.row] isEqualToString:@"关于我们"]) {
        GBAboutUsViewController *aboutUs = [[GBAboutUsViewController alloc]init];
        [self.navigationController pushViewController:aboutUs animated:YES];
    }else if (indexPath.row == 2){
        // 清除缓存
        KDClearCacheCell *cell = (KDClearCacheCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell clearCache];
    }
    
}

#pragma mark - UIActionSheetDelegate

@end
